package yushuman.rbac.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yushuman.rbac.exception.FatalException;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工具类-单例工厂
 *
 * @author 俞舒熳
 * @since 2025/6/6 19:13
 */
public class SingletonFactory {

    private static final Logger logger = LoggerFactory.getLogger(SingletonFactory.class);

    private static final Map<Class<?>, Object> instanceMap = new ConcurrentHashMap<>();

    public static <T> T getInstance(Class<T> clazz) {
        if(clazz == null) {
            logger.error("未知的类型");
            throw new FatalException();
        }
        if(!instanceMap.containsKey(clazz)) {
            try {
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                T singleton = constructor.newInstance();
                instanceMap.put(clazz, singleton);
            } catch (Exception e) {
                logger.error("创建单例失败：{}", clazz.getSimpleName(), e);
                throw new FatalException(e);
            }
        }
        @SuppressWarnings("unchecked")
        T instance = (T) instanceMap.get(clazz);
        return instance;
    }
}
